<template>
	<gui-page :fullPage="true" ref="guiPage">
		<view slot="gBody" class="chat-container">
			<!-- 聊天头部 -->
			<view class="chat-header">
				<text class="chat-title">{{ chatTitle }}</text>
				<view class="connection-status" :class="{ 'connected': isConnected }">
					{{ isConnected ? '已连接' : '未连接' }}
				</view>
			</view>
			
			<!-- 消息列表 -->
			<scroll-view 
				class="message-list" 
				scroll-y="true" 
				:scroll-top="scrollTop"
				:scroll-into-view="scrollIntoView"
				@scrolltoupper="onScrollToUpper"
			>
				<view class="message-item" 
					v-for="(message, index) in messages" 
					:key="index"
					:id="'msg_' + index"
				>
					<view class="message-wrapper" :class="{ 'is-mine': message.send_type==1 }">
						<!-- 头像 -->
						<image 
							class="avatar" 
							:src="message.user_avatar || defaultAvatar"
						></image>
						
						<!-- 消息内容 -->
						<view class="message-content">
							<!-- 用户名 -->
							<text class="username" v-if="message.send_type==1">{{ message.user_nickname }}</text>
							
							<!-- 消息气泡 -->
							<view class="message-bubble" :class="{ 'mine': message.send_type==1 }">
								<!-- 文本消息 -->
								<text v-if="message.type === 1" class="message-text">{{ message.content }}</text>
								
								<!-- 图片消息 -->
								<image 
									v-if="message.type === 2" 
									class="message-image"
									:src="message.content"
									mode="aspectFit"
									@tap="previewImage(message.content)"
								></image>
							</view>
							
							<!-- 时间戳 -->
							<text class="timestamp">{{ message.created_at }}</text>
						</view>
					</view>
				</view>
			</scroll-view>
			
			<!-- 输入区域 -->
			<view class="input-area">
				<view class="input-wrapper">
					<input 
						class="message-input"
						v-model="inputText"
						placeholder="输入消息..."
						@confirm="sendTextMessage"
						:focus="inputFocus"
					/>
					<button class="btn-image" @tap="chooseImage">
						<text class="icon-image">📷</text>
					</button>
					<button class="btn-send" @tap="sendTextMessage" :disabled="!inputText.trim()">
						发送
					</button>
				</view>
			</view>
		</view>
	</gui-page>
</template>

<script>
import graceJS from '@/GraceUI5/js/grace.js';

export default {
	data() {
		return {
			// WebSocket连接
			socketTask: null,
			isConnected: false,
			reconnectTimer: null,
			heartbeatTimer: null,
			
			// 聊天相关
			chatTitle: '聊天',
			chatId: '',
			userId: '',
			messages: [],
			inputText: '',
			inputFocus: false,
			scrollTop: 0,
			scrollIntoView: '',
			
			// 默认头像
			defaultAvatar: '/static/default_avatar.png',
			
			// 服务器配置
			wsUrl: 'wss://api.zhifuby.com/wss', // 请替换为实际的WebSocket服务器地址
		}
	},
	
	onLoad(options) {
		// 获取传入的参数
		this.chatId = options.chatId || 'default';
		this.chatTitle = options.title || '聊天';
		
		// 初始化用户信息
		this.initUserInfo();
		
		// 连接WebSocket
		this.connectWebSocket();
		
		// 加载历史消息
		this.loadHistoryMessages();
	},
	
	onUnload() {
		// 页面卸载时断开连接
		this.disconnectWebSocket();
	},
	
	onShow() {
		// 页面显示时重新连接（如果需要）
		if (!this.isConnected) {
			this.connectWebSocket();
		}
	},
	
	onHide() {
		// 页面隐藏时清除心跳
		this.clearHeartbeat();
	},
	
	methods: {
		// 初始化用户信息
		initUserInfo() {
			this.$globalMethod();
			this.userId = this.token || uni.getStorageSync('userId') || 'user_' + Date.now();
		},
		
		// 连接WebSocket
		connectWebSocket() {
			if (this.socketTask) {
				this.socketTask.close();
			}
			
			this.socketTask = uni.connectSocket({
				url: this.wsUrl,
				header: {
					'token': this.token
				},
				success: () => {
					console.log('WebSocket连接成功');
				},
				fail: (err) => {
					console.error('WebSocket连接失败:', err);
					this.reconnect();
				}
			});
			
			// 监听WebSocket事件
			this.socketTask.onOpen(() => {
				console.log('WebSocket连接已打开');
				this.isConnected = true;
				this.startHeartbeat();
				
				// 发送加入聊天室消息
				this.sendSocketMessage({
					type: 'join',
					chatId: this.chatId,
					userId: this.userId
				});
			});
			
			this.socketTask.onMessage((res) => {
				try {
					const data = JSON.parse(res.data);
					this.handleSocketMessage(data);
				} catch (error) {
					console.error('解析WebSocket消息失败:', error);
				}
			});
			
			this.socketTask.onError((err) => {
				console.error('WebSocket错误:', err);
				this.isConnected = false;
				this.reconnect();
			});
			
			this.socketTask.onClose(() => {
				console.log('WebSocket连接已关闭');
				this.isConnected = false;
				this.clearHeartbeat();
				this.reconnect();
			});
		},
		
		// 断开WebSocket连接
		disconnectWebSocket() {
			if (this.socketTask) {
				this.socketTask.close();
				this.socketTask = null;
			}
			this.isConnected = false;
			this.clearHeartbeat();
			this.clearReconnectTimer();
		},
		
		// 重连WebSocket
		reconnect() {
			this.clearReconnectTimer();
			this.reconnectTimer = setTimeout(() => {
				if (!this.isConnected) {
					console.log('尝试重连WebSocket...');
					this.connectWebSocket();
				}
			}, 3000);
		},
		
		// 清除重连定时器
		clearReconnectTimer() {
			if (this.reconnectTimer) {
				clearTimeout(this.reconnectTimer);
				this.reconnectTimer = null;
			}
		},
		
		// 开始心跳
		startHeartbeat() {
			this.clearHeartbeat();
			this.heartbeatTimer = setInterval(() => {
				if (this.isConnected) {
					this.sendSocketMessage({ type: 'ping' });
				}
			}, 30000); // 每30秒发送一次心跳
		},
		
		// 清除心跳
		clearHeartbeat() {
			if (this.heartbeatTimer) {
				clearInterval(this.heartbeatTimer);
				this.heartbeatTimer = null;
			}
		},
		
		// 发送WebSocket消息
		sendSocketMessage(data) {
			if (this.socketTask && this.isConnected) {
				this.socketTask.send({
					data: JSON.stringify(data),
					fail: (err) => {
						console.error('发送WebSocket消息失败:', err);
					}
				});
			}
		},
		
		// 处理WebSocket消息
		handleSocketMessage(data) {
			switch (data.type) {
				case 'message':
					this.addMessage(data.message);
					break;
				case 'pong':
					// 心跳响应
					break;
				case 'userJoined':
					this.showSystemMessage(data.username + ' 加入了聊天');
					break;
				case 'userLeft':
					this.showSystemMessage(data.username + ' 离开了聊天');
					break;
				default:
					console.log('未知消息类型:', data);
			}
		},
		
		// 显示系统消息
		showSystemMessage(content) {
			this.addMessage({
				type: 'system',
				content: content,
				timestamp: Date.now()
			});
		},
		
		// 加载历史消息
		loadHistoryMessages() {
			uni.request({
				url: this.serverUrl + '/api.chat/teacher_history_list',
				method: 'GET',
				header: {
					token: this.token
				},
				data: {
					user_id: this.chatId,
					page: 1,
					limit: 50
				},
				success: (res) => {
					if (res.data.code === 0) {
						const history = res.data.data || [];
						this.messages = history.map(msg => ({
							...msg,
							isMine: msg.userId === this.userId
						}));
						this.scrollToBottom();
					}
				},
				fail: (err) => {
					console.error('加载历史消息失败:', err);
				}
			});
		},
		
		// 发送文本消息
		sendTextMessage() {
			const text = this.inputText.trim();
			if (!text) return;
			
			const message = {
				type: 'text',
				content: text,
				userId: this.userId,
				chatId: this.chatId,
				timestamp: Date.now(),
				isMine: true
			};
			
			// 立即显示在界面上
			this.addMessage(message);
			
			// 通过WebSocket发送
			this.sendSocketMessage({
				type: 'message',
				message: message
			});
			
			// 清空输入框
			this.inputText = '';
		},
		
		// 选择图片
		chooseImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0];
					this.uploadImage(tempFilePath);
				},
				fail: (err) => {
					console.error('选择图片失败:', err);
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 上传图片
		uploadImage(filePath) {
			uni.showLoading({
				title: '上传中...'
			});
			
			uni.uploadFile({
				url: this.serverUrl + '/api/chat/upload',
				filePath: filePath,
				name: 'image',
				header: {
					token: this.token
				},
				formData: {
					chatId: this.chatId
				},
				success: (res) => {
					uni.hideLoading();
					try {
						const data = JSON.parse(res.data);
						if (data.code === 0) {
							const message = {
								type: 'image',
								content: data.data.url,
								userId: this.userId,
								chatId: this.chatId,
								timestamp: Date.now(),
								isMine: true
							};
							
							// 显示在界面上
							this.addMessage(message);
							
							// 通过WebSocket发送
							this.sendSocketMessage({
								type: 'message',
								message: message
							});
						} else {
							uni.showToast({
								title: data.message || '上传失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('解析上传响应失败:', error);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('上传图片失败:', err);
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 预览图片
		previewImage(url) {
			uni.previewImage({
				urls: [url],
				current: url
			});
		},
		
		// 添加消息到列表
		addMessage(message) {
			this.messages.push(message);
			this.$nextTick(() => {
				this.scrollToBottom();
			});
		},
		
		// 滚动到底部
		scrollToBottom() {
			const messageCount = this.messages.length;
			if (messageCount > 0) {
				this.scrollIntoView = 'msg_' + (messageCount - 1);
			}
		},
		
		// 滚动到顶部时加载更多历史消息
		onScrollToUpper() {
			// 这里可以实现加载更多历史消息的逻辑
			console.log('滚动到顶部，可以加载更多历史消息');
		},
		
		// 格式化时间
		formatTime(timestamp) {
			const date = new Date(timestamp);
			const now = new Date();
			const diff = now.getTime() - date.getTime();
			
			if (diff < 60000) { // 1分钟内
				return '刚刚';
			} else if (diff < 3600000) { // 1小时内
				return Math.floor(diff / 60000) + '分钟前';
			} else if (date.toDateString() === now.toDateString()) { // 今天
				return date.getHours().toString().padStart(2, '0') + ':' + 
					   date.getMinutes().toString().padStart(2, '0');
			} else {
				return (date.getMonth() + 1) + '/' + date.getDate();
			}
		}
	}
}
</script>

<style scoped>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

.chat-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	border-bottom: 1rpx solid #e5e5e5;
}

.chat-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.connection-status {
	font-size: 24rpx;
	color: #999999;
	padding: 10rpx 20rpx;
	background-color: #f0f0f0;
	border-radius: 20rpx;
}

.connection-status.connected {
	color: #4CAF50;
	background-color: #e8f5e8;
}

.message-list {
	flex: 1;
	padding: 20rpx;
}

.message-item {
	margin-bottom: 30rpx;
}

.message-wrapper {
	display: flex;
	align-items: flex-start;
}

.message-wrapper.is-mine {
	flex-direction: row-reverse;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	background-color: #e5e5e5;
}

.message-content {
	flex: 1;
	margin: 0 20rpx;
	max-width: 70%;
}

.is-mine .message-content {
	text-align: right;
}

.username {
	font-size: 24rpx;
	color: #666666;
	margin-bottom: 10rpx;
	display: block;
}

.message-bubble {
	background-color: #ffffff;
	border-radius: 20rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	display: inline-block;
	max-width: 100%;
	word-break: break-word;
}

.message-bubble.mine {
	background-color: #4CAF50;
	color: #ffffff;
}

.message-text {
	font-size: 28rpx;
	line-height: 1.4;
}

.message-image {
	max-width: 400rpx;
	max-height: 400rpx;
	border-radius: 10rpx;
}

.timestamp {
	font-size: 20rpx;
	color: #999999;
	margin-top: 10rpx;
	display: block;
}

.input-area {
	background-color: #ffffff;
	border-top: 1rpx solid #e5e5e5;
	padding: 20rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-wrapper {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.message-input {
	flex: 1;
	height: 80rpx;
	padding: 0 20rpx;
	border: 1rpx solid #e5e5e5;
	border-radius: 40rpx;
	background-color: #f8f8f8;
	font-size: 28rpx;
}

.btn-image {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	background-color: #f0f0f0;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 0;
}

.icon-image {
	font-size: 40rpx;
}

.btn-send {
	height: 80rpx;
	padding: 0 30rpx;
	background-color: #4CAF50;
	color: #ffffff;
	border: none;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.btn-send:disabled {
	background-color: #cccccc;
}
</style> 